package com.itheima.web.interceptor;

//拦截器

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.itheima.domain.db.Admin;
import com.itheima.util.ConstantUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //预处理方法
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //每一次发送请求来都带着token
        //获取请求头中的token，不存在401
        //从redis中取出token比较，如果不一致返回401
        //如果找到的token得到的admin不存在返回401
        //把admin存进adminHolder
        //redis续期
        //放行

        String token = request.getHeader("Authorization");

        if (StrUtil.isEmpty(token)) {
            response.setStatus(401);
            return false;   //不放行，结束
        }

        token = token.replace("Bearer ", ConstantUtil.ADMIN_TOKEN);
        String json = stringRedisTemplate.opsForValue().get(token);

        if (StrUtil.isEmpty(json)) {
            response.setStatus(401);
            return false;
        }

        Admin admin = BeanUtil.toBean(json, Admin.class);
        if (admin == null) {
            response.setStatus(401);
            return false;
        }

        AdminHolder.set(admin);

        stringRedisTemplate.opsForValue().set(ConstantUtil.ADMIN_TOKEN+token,json, Duration.ofHours(1));

        return true;
    }

    //最终处理的方法
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //删除线程池中的admin
        AdminHolder.remove();
    }
}
